package com.example.day2.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.BaseMenuPresenter;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.day2.R;
import com.example.day2.adapter.CommentAdapter;
import com.example.day2.adapter.GiftAdapter;
import com.example.day2.adapter.MassageAdapter;
import com.example.day2.databinding.ActivityMain2Binding;
import com.example.day2.entity.GiftResult;
import com.example.day2.entity.NormalResult;
import com.example.day2.entity.UserAccount;
import com.example.day2.entity.VideoResult;
import com.example.day2.live.view.BaoJiControl;
import com.example.day2.live.view.GiftLayout;
import com.example.day2.mvvm.base.BaseActivity;
import com.example.day2.mvvm.base.GuanZhuParam;
import com.example.day2.mvvm.utils.DBUtils;
import com.example.day2.pay.PayActivity;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;
import top.littlefogcat.danmakulib.danmaku.DanmakuView;

public class LiveActivity extends BaseActivity<ActivityMain2Binding,LiveViewModel> {

    private  VideoResult.DataBean video;
    private DanmakuContext context;
    GiftResult.DataBean item;

    private MassageAdapter massageAdapter = new MassageAdapter(R.layout.item_message);
    private GiftAdapter giftAdapter = new GiftAdapter(R.layout.item_gift);
    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {

        video = (VideoResult.DataBean) getIntent().getSerializableExtra("video");
        Glide.with(this).load(video.getHeadpath()).circleCrop().into(binding.imageLive);
        binding.name.setText(video.getAuthname());
        binding.num.setText(video.getLike_count()+"人");
        //设置信息列表
        binding.mag.setLayoutManager(new LinearLayoutManager(this));
        binding.mag.setAdapter(massageAdapter);
        //设置播放器
        binding.playerLive.getBackButton().setAlpha(0);
        binding.playerLive.getStartButton().setAlpha(0);
        binding.playerLive.setBottomProgressBarDrawable(null);
        binding.playerLive.getBackButton().setVisibility(View.GONE);
        binding.playerLive.getStartButton().setVisibility(View.GONE);
        binding.playerLive.setUp(video.getVideopath(),true,null);
        binding.playerLive.startPlayLogic();
        if(video.getDianzan() == 1){

            binding.btn.setText("已关注");
            binding.btn.setBackgroundResource(R.drawable.bg_gray_tui);
        }else{
            binding.btn.setText("关注");
            binding.btn.setBackgroundResource(R.drawable.bg_gray_an);
        }
        //点击关注
        binding.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if (video.getGuanzhu() == 1){
                   GuanZhuParam guanZhuParam = new GuanZhuParam();
                   guanZhuParam.setAuthname(video.getAuthname());
                   viewModel.getNoGuanzhu(guanZhuParam);
               }else{
                   GuanZhuParam guanZhuParam = new GuanZhuParam();
                   guanZhuParam.setAuthname(video.getAuthname());
                   viewModel.getGuanzhu(guanZhuParam);
               }
            }
        });

        binding.kiv.addLikeImages(R.drawable.fav_0,R.drawable.fav_1,R.drawable.fav_2,R.drawable.fav_3,R.drawable.fav_4,R.drawable.fav_5);
        binding.ivLove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.kiv.addFavor();
            }
        });
        //弹幕
        binding.ivDanmu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = binding.et.getText().toString();
                //发消息
                String username = SPUtils.getInstance().getString("username");
                massageAdapter.getData().add(username + "说："+s);
                massageAdapter.notifyDataSetChanged();
                binding.mag.scrollToPosition(massageAdapter.getData().size()-1);

                //弹幕
                simpledanmu(s);
                lieyan(s);
                //发送环信消息
                EMMessage message = EMMessage.createTxtSendMessage(s, video.getAuthname());
                EMClient.getInstance().chatManager().sendMessage(message);

            }
        });


        context = DanmakuContext.create();
        BaseDanmakuParser base = new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        };
        binding.dv.prepare(base,context);

        //加载礼物列表
        binding.ivGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.sha.setVisibility(View.VISIBLE);

            }
        });

        binding.close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.sha.setVisibility(View.GONE);
            }
        });
        binding.rvList.setAdapter(giftAdapter);
        binding.rvList.setLayoutManager(new StaggeredGridLayoutManager(5,StaggeredGridLayoutManager.VERTICAL));
        viewModel.getGift();

        //点击礼物
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                 item = giftAdapter.getItem(position);
                //判断账号金额
                String user = SPUtils.getInstance().getString("username");
                UserAccount query = DBUtils.getInstance().getUserAccountDao().getQuery(user);
                if (query == null || query.getMoney() < item.getPrice()){
                    ToastUtils.showLong("余额不足,请充值!");
                }else{
                    binding.tvSelectGift.setText(item.getGiftname());
                    Glide.with(LiveActivity.this).load(item.getGiftpath()).into(binding.ivSelectGift);
                    Glide.with(LiveActivity.this).load(item.getGiftpath()).into(binding.giftFei);
                }

            }
        });
        //初始化暴击
        BaoJiControl baoJiControl = new BaoJiControl(this, binding.gl);

        //发送礼物
        binding.btnSelsectGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baoJiControl.sendGift(item);

                String user = SPUtils.getInstance().getString("username");
                UserAccount query = DBUtils.getInstance().getUserAccountDao().getQuery(user);
                double v1 = query.getMoney() - item.getPrice();
                query.setMoney(v1);
                DBUtils.getInstance().getUserAccountDao().add(query);
                binding.account.setText("金额："+v1+"抖币");

                //获取屏幕的大小
                int width = getWindowManager().getDefaultDisplay().getWidth();
                int height = getWindowManager().getDefaultDisplay().getHeight();

                //动画。移动到屏幕中间，旋转透明
                ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(binding.giftFei, "translationX", 0, width /3*  2).setDuration(3000);
                ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(binding.giftFei, "translationY", height, -height / 3* 2).setDuration(3000);
                ObjectAnimator objectAnimator3 = ObjectAnimator.ofFloat(binding.giftFei, "rotation", 0, 300).setDuration(3000);
                ObjectAnimator objectAnimator4 = ObjectAnimator.ofFloat(binding.giftFei, "alpha", 1, 0).setDuration(6000);
                binding.giftFei.setVisibility(View.VISIBLE);
                AnimatorSet animatorSet = new AnimatorSet();
                animatorSet.play(objectAnimator1).with(objectAnimator2).with(objectAnimator3).with(objectAnimator4);
                animatorSet.start();
            }
        });




        //充值

        binding.cz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LiveActivity.this, PayActivity.class);
                startActivity(intent);
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        String user = SPUtils.getInstance().getString("username");
        UserAccount query = DBUtils.getInstance().getUserAccountDao().getQuery(user);
        if (query != null){
            binding.account.setText("金额："+query.getMoney()+"抖币");
        }else{
            ToastUtils.showLong("充值");
        }
    }

    private boolean isStarted = false;
    private void lieyan(String s) {
        BaseDanmaku danmaku = context.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        danmaku.text = s;
        danmaku.borderColor = Color.YELLOW;
        danmaku.underlineColor = Color.RED;
        danmaku.textColor = Color.BLUE;
        danmaku.setTime(binding.dv.getCurrentTime());
        binding.dv.addDanmaku(danmaku);
        binding.dv.start();

    }

    private void simpledanmu(String s) {
        Danmaku danmaku = new Danmaku();
        danmaku.mode = Danmaku.Mode.scroll;
        danmaku.text = s;
        danmaku.size = 32;
        danmaku.color = Danmaku.COLOR_YELLOW;
        DanmakuManager.getInstance().init(this,binding.fi);
        DanmakuManager.getInstance().send(danmaku);
        binding.et.setText(null);
        if (!isStarted){
            binding.dv.start();
            isStarted = true;
        }

    }

    @Override
    public void initData() {
        //礼物列表加载成功
        viewModel.GiftSuccess.observe(this, new Observer<GiftResult>() {
            @Override
            public void onChanged(GiftResult giftResult) {
                if (giftResult.getCode() == 200){
                    giftAdapter.getData().addAll(giftResult.getData());
                    giftAdapter.notifyDataSetChanged();
                }

            }
        });
        viewModel.GuaSuccess.observe(this, new Observer<NormalResult>() {
            @Override
            public void onChanged(NormalResult normalResult) {
                if (normalResult.getCode() == 200){
                    video.setGuanzhu(1);
                    binding.btn.setText("已关注");
                    int numm = video.getLike_count();
                    binding.num.setText(numm+"人");
                    binding.btn.setBackgroundResource(R.drawable.bg_gray_tui);
                }
            }
        });
        viewModel.GuanSuccess.observe(this, new Observer<NormalResult>() {
            @Override
            public void onChanged(NormalResult normalResult) {
                if (normalResult.getCode() == 200){
                    video.setGuanzhu(0);
                    binding.btn.setText("关注");
                    int num2 = video.getLike_count()- 1;
                    binding.num.setText(num2+"人");
                    binding.btn.setBackgroundResource(R.drawable.bg_gray_an);
                }
            }
        });

    }

    @Override
    public Class<LiveViewModel> getVIewModel() {
        return LiveViewModel.class;
    }

    @Override
    public int bindLayoutId() {
        return R.layout.activity_main2;
    }
}